from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone

from allauth.account.models import EmailAddress


class UserProfile(AbstractUser):
    """ 用户资料信息 """
    
    # 用户性别
    DEFAULT_GENDER = 'Male'
    GENDER_CHOICES = (('Male', '男'), ('Female', '女'))

    # 用户昵称
    DEFAULT_NICKNAME = 'Guest'
    
    # 所在公司
    DEFAULT_COMPANY = "十露盘科技科技有限公司"
    
    # 所在部门
    DEFAULT_DEPARTMENT = 'Other'
    DEPARTMENT_CHOICES = (('Algorithm', '算法部'),
                          ('Business', '商务部'),
                          ('Data', '数据部'),
                          ('Leader', '管理部'),
                          ('Model', '模型部'),
                          ('Operation', '运营部'),
                          ('Product', '产品部'),
                          ('Risk', '风控部'),
                          ('Strategy', '策略部'),
                          ('Technology', '技术部'),
                          ('Test', '测试部'),
                          ('Integration', '综合部'),
                          ('Other', '其它部门'))

    # 设置账号过期时间
    ACCOUNT_EXPIRE_TIME = timezone.datetime(2030, 1, 1, 0, 0, 0)
    
    user_id = models.CharField('用户编号', primary_key=True, null=False)
    avatar = models.ImageField(upload_to='image/%Y/%m/%d', max_length=256, default='image/default.png')
    nickname = models.CharField(help_text='用户昵称', max_length=64, default=DEFAULT_NICKNAME)
    real_name = models.CharField(help_text='真实姓名', max_length=64, default=DEFAULT_NICKNAME)
    birthday = models.DateField(help_text='出生日期', blank=True, null=True)
    gender = models.CharField(help_text='用户性别', default=DEFAULT_GENDER, choices=GENDER_CHOICES)
    mobile = models.CharField(help_text='手机号码', max_length=11, null=True, unique=True, blank=False)
    company = models.CharField(help_text='公司名称', max_length=256, default=DEFAULT_COMPANY)
    department = models.CharField('所在部门', max_length=32, choices=DEPARTMENT_CHOICES, default=DEFAULT_DEPARTMENT)
    address = models.CharField(help_text='居住地址', max_length=256, blank=True, null=True)
    is_leader = models.BooleanField(help_text='是否是部门领导', default=False)
    expire_time = models.DateTimeField('资料账户过期时间', default=ACCOUNT_EXPIRE_TIME)
    # last_login = models.DateTimeField('最近登录时间', blank=True, null=True)
    update_time = models.DateTimeField('记录更新时间', auto_now_add=False, auto_now=True)

    def __str__(self):
        return self.username

    def account_verified(self):
        """ 提示用户邮箱是否验证"""
        if self.is_authenticated:
            result = EmailAddress.objects.filter(email=self.email)
            if result:
                return result[0].verified
        return False

    class Meta:
        # App 名称
        app_label = "userManage"

        # 抽象基类
        abstract = False

        # 数据表名
        db_table = "user_profile"

        # 查询数据的排序字段
        get_latest_by = ['username', 'update_time']

        # 默认由命令行管理工具迁徙(default: True)
        managed = True

        # 模型排序字段
        ordering = ['date_joined', 'update_time']

        # 约束: 多键组合唯一约束
        unique_together = ['username', 'company', 'department', 'email']

        # 页面展示名称: verbose
        verbose_name = "用户资料"


class Menu(models.Model):
    """ 定义 项目站点主界面中 [左侧 or 上方] 菜单中功能模块"""
    
    id = models.AutoField('自增主键', primary_key=True)
    level_1st_menu = models.CharField('一级菜单', max_length=64, default=None)
    level_2nd_menu = models.CharField('二级菜单', max_length=64, default=None)
    level_3rd_menu = models.CharField('三级菜单', max_length=64, default=None)
    update_time = models.DateTimeField('记录更新时间', auto_now_add=False, auto_now=True)

    def __int__(self):
        return '{0}.{1}.{2}'.format(self.level_2nd_menu, self.level_2nd_menu, self.level_3rd_menu)

    class Meta:
        # App 名称
        app_label = "userManage"
        
        # 抽象基类
        abstract = True


class SideBarMenu(Menu):
    """ 定义侧边栏展示功能菜单"""

    class Meta:
        # App 名称
        app_label = "userManage"
        
        # 抽象基类
        abstract = False
        
        # 数据表名
        db_table = "left_sidebar_menu"
        
        # 查询数据的排序字段
        get_latest_by = ['menu', 'submenu']
        
        # 默认由命令行管理工具迁徙(default: True)
        managed = True
        
        # 模型排序字段
        ordering = ['id', 'update_time']
        
        # 约束: 多键组合唯一约束
        unique_together = ['menu', 'submenu']
        
        # 页面展示名称: verbose
        verbose_name = "左侧菜单"


class TopBarMenu(Menu):
    """定义 顶部菜单 """
    class Meta:
        # App 名称
        app_label = "userManage"
    
        # 抽象基类
        abstract = False
    
        # 数据表名
        db_table = "top_bar_menu"

        # 查询数据的排序字段
        get_latest_by = ['menu', 'submenu']
    
        # 默认由命令行管理工具迁徙(default: True)
        managed = True
    
        # 模型排序字段
        ordering = ['id', 'update_time']
    
        # 约束: 多键组合唯一约束
        unique_together = ['menu', 'submenu']
    
        # 页面展示名称: verbose
        verbose_name = "顶部菜单"


class UserMenuPrivilege(models.Model):
    """
    用户权限类:  不同用户对于 访问本项目站点中不同功能模块的权限管理控制工作. (若需要动态拓展, 可参考
                django.contrib.auth.models 中 UserManager, Permission 等 研究, 进行扩展).
    """

    # 设置用户权限过期时间
    PRIVILEGE_EXPIRE_TIME = timezone.datetime(2030, 1, 1, 0, 0, 0)

    user_id = models.CharField(UserProfile, on_delete=models.CASCADE)
    menu = models.ManyToManyField(Menu)
    submenu = models.ManyToManyField(Menu)
    is_activate = models.BooleanField('是否激活', default=True)
    expired_time = models.DateTimeField('设置权限过期时间', default=PRIVILEGE_EXPIRE_TIME)
    is_expired = models.BooleanField('权限是否过期', default=False)
    update_time = models.DateTimeField('记录更新时间', auto_now_add=False, auto_now=True)

    def __int__(self):
        return '{0}.{1}.{2}'.format(self.user_id, self.menu, self.submenu)

    class Meta:
        # App 名称
        app_label = "userManage"
    
        # 抽象基类
        abstract = False
    
        # 数据表名
        db_table = "user_menu_privilege"
    
        # 查询数据的排序字段
        get_latest_by = ['user_id', 'menu', 'submenu']
    
        # 默认由命令行管理工具迁徙(default: True)
        managed = True
    
        # 模型排序字段
        ordering = ['id', 'update_time']

        # 约束: 多键组合唯一约束
        unique_together = ['user_id', 'menu', 'submenu']

        # 页面展示名称: verbose
        verbose_name = "菜单权限"
